package com.atguigu.srb.core.linstener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
//@AllArgsConstructor //全参
@NoArgsConstructor //无参
// 有个很重要的点 ExcelDictDTOListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
//所以我们不能使用@resource直接注入mapper 需要创建构造函数
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {
    private DictMapper dictMapper;
    List<ExcelDictDTO> list=new ArrayList<>();
    private static final int BATCH_COUNT=5;

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        log.info("数据{}",excelDictDTO);
        list.add(excelDictDTO);
        if (list.size()>=BATCH_COUNT){
            //调用mapper的层save方法
            saveData();
            list.clear();
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //最后的数据不足BATCH_COUNT，收尾时再存入
        saveData();
        list.clear();
        log.info("存储数据库成功！");
    }

    private void saveData(){
        log.info("存入{}",list.size());
        //调用mapper的层save方法
        dictMapper.insertBatch(list);
        log.info("存入{}条数据成功",list.size());
    }
}
